package com.infore.statisticsAndAlarm.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.infore.statisticsAndAlarm.constant.Constants;
import com.infore.statisticsAndAlarm.dto.AirInstructionsDataDto;
import com.infore.statisticsAndAlarm.enums.ResultStatus;
import com.infore.statisticsAndAlarm.enums.WaterQualityTargetLevel;
import com.infore.statisticsAndAlarm.externalInterface.IStieMangementService;
import com.infore.statisticsAndAlarm.repository.IHourDataAirRepository;
import com.infore.statisticsAndAlarm.select.dto.QueryParamDto;
import com.infore.statisticsAndAlarm.select.util.PageObject;
import com.infore.statisticsAndAlarm.select.util.QueryCondition;
import com.infore.statisticsAndAlarm.service.IGisDataService;
import com.infore.statisticsAndAlarm.util.ArrayUtils;
import com.infore.statisticsAndAlarm.util.DateUtil;
import com.infore.statisticsAndAlarm.util.GetAQI;
import com.infore.statisticsAndAlarm.util.JsonUtils;
import com.infore.statisticsAndAlarm.util.ObjectMapperUtil;
import com.infore.statisticsAndAlarm.util.Page;
import com.infore.statisticsAndAlarm.util.PageUtil;
import com.infore.statisticsAndAlarm.util.ResultEntity;

@Service
public class GisDataServiceImpl implements IGisDataService{

	@Autowired
	private IHourDataAirRepository iHourDataAirRepository;
	@Autowired
	private IStieMangementService iStieMangementService ;
	@Autowired
	private ObjectMapperUtil objectMapperUtil;

	public ResultEntity queryHourDataAir(String mn, String isNnusual, PageObject pageObject) throws IOException {
        Calendar c = Calendar.getInstance();
        Date endTime = new Date();
        c.setTime(endTime);
        c.add(Calendar.DAY_OF_MONTH, -30);
        List<String> mnsQuery = ArrayUtils.stringToList(mn);
        String start = DateUtil.dateToString(c.getTime(), DateUtil.DATE_SMALL_STR);
        String end = DateUtil.dateToString(endTime, DateUtil.DATE_SMALL_STR);
        List<Map<String, Object>> list = iHourDataAirRepository.queryNewData(mnsQuery, start, end);
        //
        QueryParamDto queryParamDto = JsonUtils.readJsonFromClassPath("/param/siteQueryBasic.json", QueryParamDto.class);
        QueryCondition q = new QueryCondition();
        String mnList = "stationMn", oper ="in";
        q.setOperator(Arrays.asList(oper));
        q.setProperty(Arrays.asList(mnList));
        q.setContent(Arrays.asList(mn));
        queryParamDto.setQueryCondition(q);
        ResultEntity resultEntity = iStieMangementService.queryStation(queryParamDto);
        Map<String, Object> dataMap = (Map<String, Object>)resultEntity.getContent();
        List<Map<String, Object>> siteList = (List<Map<String, Object>>)dataMap.get("dataList");
        Map<String, Map<String, Object>> siteMap = new HashMap<>();
        for(Map<String, Object> map:siteList) {
            siteMap.put(map.get("stationMn").toString(), map);
        }
        List<AirInstructionsDataDto> unualList = new ArrayList<>();
        List<AirInstructionsDataDto> normalList = new ArrayList<>();
        List<AirInstructionsDataDto> finalList = new ArrayList<>();
        SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(Map<String, Object> map:list) {
            String mns = map.get("MN").toString();
            List<AirInstructionsDataDto> dtoList = new ArrayList<AirInstructionsDataDto>();
            AirInstructionsDataDto waterInstructionsDataDto = new AirInstructionsDataDto();
			String provinceName = siteMap.get(mns).get("provinceId_areaName") == null ? "" : siteMap.get(mns).get("provinceId_areaName").toString();
			waterInstructionsDataDto.setProvince(provinceName);
			waterInstructionsDataDto.setBasin(siteMap.get(mns).get("basinn_basinnName").toString());
			waterInstructionsDataDto.setStationName(siteMap.get(mns).get("stationName").toString());
			waterInstructionsDataDto.setCityName(siteMap.get(mns).get("cityName")==null?null:siteMap.get(mns).get("cityName").toString());
			waterInstructionsDataDto.setAreaName(siteMap.get(mns).get("areaName")==null?null:siteMap.get(mns).get("areaName").toString());
            String targerWaterQuality = siteMap.get(mns).get("targerWaterQuality") == null ? "-" : siteMap.get(mns).get("targerWaterQuality").toString();
            waterInstructionsDataDto.setStationName(siteMap.get(mns).get("stationName").toString());
            waterInstructionsDataDto.setTargerWaterQuality(targerWaterQuality);
            waterInstructionsDataDto.setMn(map.get("MN")==null?null:map.get("MN").toString());
           waterInstructionsDataDto.setDataTime(sdfDateFormat.format((Date)map.get("DATA_TIME")));
            waterInstructionsDataDto.setStationState("0");
            Map<String, Double> calAqi = new HashMap<String, Double>();
            String PM10 = map.get("PM10")==null?null:map.get("PM10").toString();  //
            String PM25 = map.get("PM25")==null?null:map.get("PM25").toString(); //
            String CO = map.get("CO")==null?null:map.get("CO").toString();;  //
            String NO2 = map.get("NO2")==null?null:map.get("NO2").toString();;  //
            String SO2 = map.get("SO2")==null?null:map.get("SO2").toString();;  //
            String O3 = map.get("O3")==null?null:map.get("O3").toString();;  //
            waterInstructionsDataDto.setPM10(PM10);
            waterInstructionsDataDto.setPM25(PM25);
            waterInstructionsDataDto.setNO2(NO2);;
            waterInstructionsDataDto.setCO(CO);;
            waterInstructionsDataDto.setO3(O3);;
            waterInstructionsDataDto.setSO2(SO2);
            calAqi.put("PM10", NumberUtils.createDouble(PM10));
            calAqi.put("PM25", NumberUtils.createDouble(PM25));
            calAqi.put("CO", NumberUtils.createDouble(CO));
            calAqi.put("NO2", NumberUtils.createDouble(NO2));
            calAqi.put("SO2", NumberUtils.createDouble(SO2));
            calAqi.put("O3", NumberUtils.createDouble(O3));
            String primaryPollution = GetAQI.getPrimaryPollution(calAqi);
            waterInstructionsDataDto.setPrimaryPollutant(primaryPollution);
            dtoList.add(waterInstructionsDataDto);
            //判断单个因子是不是超标
            //暂时单个因子的超标等级限制为三级
            int singlLevel = 3;
            String PM10State = getUnusal("PM10", PM10, singlLevel);
            String PM25State = getUnusal("PM25", PM25, singlLevel);
            String COState = getUnusal("CO", CO, singlLevel);
            String NO2State = getUnusal("NO2", NO2, singlLevel);
            String SO2State = getUnusal("SO2", SO2, singlLevel);
            String O3State = getUnusal("O3", O3, singlLevel);
            waterInstructionsDataDto.setPM10State(PM10State);;
            waterInstructionsDataDto.setPM25State(PM25State);;
            waterInstructionsDataDto.setNO2State(NO2State);;
            waterInstructionsDataDto.setCOState(COState);
            waterInstructionsDataDto.setSO2State(SO2State);;
            waterInstructionsDataDto.setO3State(O3State);
            //计算综合水质等级
            int realLevel = GetAQI.getAQIMap(calAqi);
            waterInstructionsDataDto.setAqi(realLevel);
            String evaluation = GetAQI.getPollutionLevel(realLevel);
            waterInstructionsDataDto.setEvaluation(evaluation);
            String level = realLevel+"";
            String flag = "normal";
            //判断整条记录是不是超标数据
            if(NumberUtils.isNumber(level)) {
                String arm = WaterQualityTargetLevel.getDesc(targerWaterQuality).getStatusCode();//目标水质等级
                int armLevel = NumberUtils.createInteger(arm);
                int levelInt = NumberUtils.createInteger(level);//实际等级
                flag = levelInt > armLevel ? "unusual":"normal";
                waterInstructionsDataDto.setIsNnusual(flag);
            }
            if ("unusual".equals(flag)) {
                unualList.add(waterInstructionsDataDto);
            } else if("normal".equals(flag)){
                normalList.add(waterInstructionsDataDto);
            }
            finalList.add(waterInstructionsDataDto);
        }
        if ("unusual".equals(isNnusual)) {
            finalList = unualList;
        } else if("normal".equals(isNnusual)){
            finalList = normalList;
        }
        if (pageObject!=null && pageObject.getPageNumber()!=null&&pageObject.getPageSize()!=null) {
			Page<AirInstructionsDataDto> page = PageUtil.inventedObjectPage(finalList, pageObject);
			 return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setPage(page);
		}else {
			 return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(finalList);
		}
       
    }
	
	String getUnusal(String name,String value,int level) {
		if (value == null) {
			return "normal";
		}
		Double valuDouble = NumberUtils.createDouble(value);
		int aqi = GetAQI.getIAQI(name, valuDouble);
		String reavLevel = GetAQI.getPollutionNumLevel(aqi);
		if ("一级".equals(reavLevel) || "二级".equals(reavLevel) || "三级".equals(reavLevel)) {
			return "normal";
		} else {
			return "unusual";
		}
	}
}
